package com.foreveross.smsh.core.web;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.foreveross.smsh.common.JsonUtil;
import com.foreveross.smsh.common.Paginator;

/**
 * Action基础类,系统里所有Action都必须继承该Action
 * @author zhangle
 */
public abstract class BaseAction {
	private static final Logger logger = LogManager.getLogger(BaseAction.class);
	
	
	protected String forward(String path) {
		return "forward:"+path;
	}
	
	protected String redirect(String path) {
		return "redirect:"+path;
	}
	
	public HttpServletRequest getRequest() {
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return request;
	}
	
	public HttpServletResponse getResponse() {
		HttpServletResponse response = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
		return response;
	}
	
	protected HttpSession getSession() {
		return getRequest().getSession();
	}
	
	protected ServletContext getServletContext() {
		return getSession().getServletContext();
	}
	
	/**
	 * 获取真实路径
	 */
	protected String getRealPath(String path) {
		return getServletContext().getRealPath(path);
	}
	
	/**
	 * 获取请求参数
	 */
	protected String param(String name) {
		return getRequest().getParameter(name);
	}
	
	/**
	 * 获取请求参数数组
	 */
	protected String[] params(String name) {
		return getRequest().getParameterValues(name);
	}
	
	/**
	 * 获取int类型请求参数
	 */
	protected int intParam(String name) {
		return Integer.parseInt(param(name));
	}

	/**
	 * 获取int类型请求参数,当出错时,返回defaultValue
	 */
	protected int intParam(String name,int defaultValue) {
		try {
			return Integer.parseInt(param(name));
		} catch(Exception e) {
			return defaultValue;
		}
	}
	
	/**
	 * 设置attribute到request中
	 */
	protected void attr(String name,Object value) {
		getRequest().setAttribute(name, value);
	}
	
	/**
	 * 从request中获取attribute
	 */
	protected Object attr(String name) {
		return getRequest().getAttribute(name);
	}
	
	/**
	 * 设置attribute到session中
	 */
	protected void sessAttr(String name,Object value) {
		getSession().setAttribute(name, value);
	}
	
	/**
	 * 从session中获取attribute
	 */
	protected Object sessAttr(String name) {
		return getSession().getAttribute(name);
	}
	
	/**
	 * 设置attribute到application中
	 */
	protected void appAttr(String name,Object value) {
		getServletContext().setAttribute(name, value);
	}
	
	/**
	 * 从application中获取attribute
	 */
	protected Object appAttr(String name) {
		return getServletContext().getAttribute(name);
	}
	
	/**
	 * 获取ip
	 * @param request
	 * @return
	 */
	public static String getIp(HttpServletRequest request) {
		
		if (request == null) return "";
		String ip =  request.getRemoteAddr();
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Forwarded-For");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (StringUtils.isEmpty(ip) || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		
		return ip;
	}
	
	/**
	 * 打印json字符到response
	 */
	protected void printJson(Object obj) {
		try {
			HttpServletResponse response =this.getResponse();
			response.setContentType("text/json; charset=utf-8");
			response.setCharacterEncoding("utf-8");
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
			response.setDateHeader("Expires",-1);
			
			if(obj instanceof String) {
				response.getWriter().print((String)obj);
			} else if(obj instanceof Paginator) {
				Paginator pagin=(Paginator<?>)obj;
				Map<String, Object> jsonMap=new HashMap<String, Object>();
				jsonMap.put("total", pagin.getTotalCount());
				jsonMap.put("rows", pagin.getDataList());
				response.getWriter().println(JsonUtil.toJson(jsonMap));
			} else {
				response.getWriter().println(JsonUtil.toJson(obj));
			}
		} catch (Exception e) {
			throw new RuntimeException("输出json数据出错!",e);
		}
	}
	
	
	/**
	 * 错误处理
	 */
	@ExceptionHandler(Exception.class)
	protected void handleException(HttpServletRequest request,HttpServletResponse response,Exception e) {
		logger.error(e.getMessage(),e); 
		printErrorMessage(request,response,e.getMessage());
	}
	
	/**
	 * 输出错误消息
	 * @param request
	 * @param response
	 * @param result
	 */
	private void printErrorMessage(HttpServletRequest request,HttpServletResponse response,String result) {
		
		response.setContentType("text/json; charset=utf-8");
		response.setCharacterEncoding("utf-8");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
		response.setDateHeader("Expires",-1);
		
		try {
			String callback=request.getParameter("callback");
			if(StringUtils.isEmpty(callback)) {
				response.getWriter().print(result);
				response.getWriter().flush();
			} else {		//否则以jsonp格式输出消息
				response.getWriter().print(callback+"("+result+")");
				response.getWriter().flush();
			}
		} catch (IOException e) {
			logger.error(e.getMessage(),e);
		}
	}
}
